<?php
/**
 * Created by PhpStorm.
 * User: xiaoxin
 * Date: 2018/10/24 0024
 * Time: 14:18
 */


class Mysql{
	public $where;
	public $dbname;
	public static $db=null;

	function __construct($dbname){
		if (!self::$db){
			self::$db = new PDO("mysql:host=127.0.0.1;dbname=school;charset=utf8","root","root");
		}
		$this->dbname = $dbname;
	}

	/**
	 * 插入数据方法
	 * @param array $data  传过来的参数为数组
	 */
	public function save($data=array()){
		if (!is_array($data)){
			exit('插入的数据必须为数组');
		}
		$str = implode(array_keys($data),',');
		$values = implode($data,'\',\'');
		$sql = self::$db->exec('insert into '.$this->dbname.'('.$str.')'.'values'.'(\''.$values.'\')');
		if (!$sql){
			exit('出现错误,系统即将爆炸,请传正确的数据行不行？');
		}else{
			var_dump('OK');
		}
	}

	/**
	 * 删除数据
	 * @param array $data
	 */
	public function del($data=array()){
		if (is_array($data)){
			$str = implode(array_keys($data),',');
			$values = implode($data,',');
			$sql = self::$db->exec('delete from '.$this->dbname.' where '.$str.'=\''.$values.'\'');
			if (!$sql){
				exit('出现错误,系统即将爆炸,请传正确的数据行不行？');
			}else{
				var_dump('OK');
			}
		}elseif(is_int($data)){
			$sql = self::$db->exec('delete from '.$this->dbname.' where id ='.''.$data.'');
			if (!$sql){
				exit('出现错误,系统即将爆炸,请传正确的数据行不行？');
			}else{
				var_dump('OK');
			}
		}else{
			exit('系统异常，即将爆炸');
		}
	}

	/**
	 * 查数据
	 * @param null $data
	 */
	public function select($data=null){
		if ($data==null){
			$sql = self::$db->query('select * from '.$this->dbname);
			$res = $sql->fetchAll(PDO::FETCH_ASSOC);
			if (!$res){
				exit('出现错误,系统即将爆炸,请传正确的数据行不行？');
			}else{
				var_dump('OK');
			}
		}elseif(is_array($data)){
			$str = implode(array_keys($data),',');
			$values = implode($data,',');
			$sql = self::$db->query('select * from '.$this->dbname.' where '.$str.'=\''.$values.'\'');
			$res = $sql->fetchAll(PDO::FETCH_ASSOC);
			if (!$res){
				exit('出现错误,系统即将爆炸,请传正确的数据行不行？');
			}else{
				var_dump('OK');
			}
		}
	}

	/**
	 * 更新表
	 * @param $data  需要更改的字段
	 * @param $save  需要更改条件
	 */
	public function updata($data,$save){
		$str = implode(array_keys($data),',');
		$values = implode($data,',');
		$saves = implode(array_keys($save),',');
		$saves_values = implode($save,',');
		$sql = self::$db->exec('update '.$this->dbname.' set '.$str.'=\''.$values.'\' where '.$saves.'=\''.$saves_values.'\'');
		if (!$sql){
			exit('出现错误,系统即将爆炸,请传正确的数据行不行？');
		}else{
			var_dump('OK');
		}
	}
}
$sql = new Mysql('stu');
//$sql->updata(['name'=>'小王'],['name'=>'小王八']);
//$sql->select(['name'=>'小王']);
//$sql->del(['name'=>'小王5']);
//$sql->save(['name'=>'小王','sex'=>'男','age'=>17]);